package cn.doitedu.javase.thread;

/**
 * @Author: 深似海
 * @Site: <a href="www.51doit.com">多易教育</a>
 * @QQ: 657270652
 * @Date: 2024/2/2
 * @Desc: 学大数据，上多易教育
 * <p>
 * 用一个线程充当售票员
 * 用4个线程充当购票人
 * <p>
 * 初始票数为100张
 * <p>
 * 然后模拟整个卖票过程，直到票卖完为止
 * 程序退出前，售票员要打印出 总共卖出的票数
 * 每个购票人，要打印出总共购买的票数
 **/
public class _03_线程同步练习 {
    public static void main(String[] args) {

        Seller seller = new Seller();

        new Thread(new Buyer(seller, "张三")).start();
        new Thread(new Buyer(seller, "李四")).start();
        new Thread(new Buyer(seller, "王五")).start();
        new Thread(new Buyer(seller, "赵六")).start();


    }

}

class Seller {
    Integer ticketNumb = 100;

    public synchronized int sell() {
        int tmp = ticketNumb;
        ticketNumb--;

        if(ticketNumb >= -1) {
            System.out.println("卖出了一张票: " + tmp);
        }

        return tmp;
    }
}


class Buyer implements Runnable {

    Seller seller;
    String name;

    public Buyer(Seller seller, String name) {
        this.seller = seller;
        this.name = name;
    }

    @Override
    public void run() {
        int ticketNum;
        while ((ticketNum = seller.sell()) >= 0) {
            System.out.println(name + " 买到一张票： " + ticketNum);
        }
    }
}


